<script setup lang="ts">
  import { ref, onActivated, computed, onDeactivated } from 'vue';
  import { getCurrencyList, getQueryTokens, getQueryCarbonTrading } from '/@/apis/userApi';
  import { useRequest } from 'vue-request';
  import { useRouter } from 'vue-router';
  const imgsmap = JSON.parse(localStorage.getItem('tokensImgsMap') as string) || {};
  const timer = ref();
  const router = useRouter();
  const times = () => {
    timer.value = setInterval(methodCurrencyList, 5000);
  };
  const currencyList = ref<any[]>([]);
  const carbonTradingList = ref<any[]>([]);
  const tokensList = ref<any[]>([]);
  const tokensAndcarbonTradingList = ref<any[]>([]);
  onActivated(() => {
    methodCurrencyList(true);
    times();
  });
  onDeactivated(() => {
    clearInterval(timer.value);
    timer.value = null;
  });
  const list = computed(() => {
    if (tabsActive.value == 'Cryptocurrencies') {
      return tokensAndcarbonTradingList.value;
    }
    if (tabsActive.value == 'Futures') {
      return carbonTradingList.value;
    }
    return currencyList.value;
  });
  const props = defineProps<{ type: string }>();
  const tabsActive = computed(() => props.type);
  function toTrade(val: any) {
    console.log(val);
    localStorage.setItem('trade', JSON.stringify(val));
    router.push({
      path: '/trade',
    });
  }
  // 获取期货外汇列表
  function methodCurrencyList(val?: any) {
    if (tabsActive.value == 'Forex' || val) {
      useRequest(getCurrencyList, {
        onSuccess: function (data: any) {
          if (!data.data.length) return;
          currencyList.value = data.data;
        },
      });
    }
    if (tabsActive.value == 'Cryptocurrencies' || val) {
      // 加密货币列表
      useRequest(getQueryCarbonTrading, {
        onSuccess: function (data: any) {
          let carbonTradingList = [] as { [key: string]: any }[];
          data.forEach((item: { [key: string]: any }) => {
            if (item.symbol == 'XAU') {
              carbonTradingList.unshift(item);
            } else {
              carbonTradingList.push(item);
            }
          });
          useRequest(getQueryTokens, {
            onSuccess: function (data: any) {
              let datas = data as { [key: string]: any }[];
              tokensList.value = datas.map((item) => {
                item.name = item.pairsName;
                return item;
              });
              tokensAndcarbonTradingList.value = [...carbonTradingList, ...tokensList.value];

              if (!localStorage.getItem('tokensImgsMap')) {
                let tokensImgsMap: { [xx: string]: any } = {};
                tokensList.value.forEach((item) => {
                  tokensImgsMap[item.tokenCur] = item.baseCurrencyId;
                });
                localStorage.setItem('tokensImgsMap', JSON.stringify(tokensImgsMap));
              }
            },
          });
        },
      });
    }
    if (tabsActive.value == 'Futures' || val) {
      // 获取期货列表
      useRequest(getQueryCarbonTrading, {
        onSuccess: function (data: any) {
          carbonTradingList.value = data;
        },
      });
    }
  }
  // 转换单位
  const handleUnit = (value: any) => {
    let newValue = '';
    if (!value) {
      newValue = '0';
    } else if (Number(value) >= 1000000000) {
      newValue = (Number(value) / 1000000000).toFixed(2) + 'B';
    } else if (Number(value) < 1000000) {
      newValue = (Number(value) / 1000).toFixed(2) + 'K';
    } else {
      newValue = (Number(value) / 1000000).toFixed(2) + 'M';
    }
    return newValue;
  };
</script>
<template>
  <div class="maketsList">
    <div class="maketsList-list">
      <div class="li" @click="toTrade(item)" v-for="(item, index) in list" :key="index">
        <div class="img_box" v-if="!item.type && item.name">
          <div class="flag flag1">
            <img :src="$img(`country/${item.name.split('/')[0]}.png`)" alt="" />
          </div>
          <div class="flag flag2">
            <img :src="$img(`country/${item.name.split('/')[1]}.png`)" alt="" />
          </div>
        </div>
        <div class="img_box" v-else-if="item.type == 'CONTRACT'">
          <div class="flag1">
            <img
              :src="`https://s2.coinmarketcap.com/static/img/coins/64x64/${
                imgsmap[item.name.split('/')[0]]
              }.png`"
              alt=""
            />
          </div>
        </div>
        <div class="img_box" v-else-if="item.type == 'CARBON_TRADING'">
          <div class="flag1">
            <img :src="`/${item.symbol}.png`" />
          </div>
        </div>

        <!-- <div class="width1">
          <p class="p1">{{
            item.baseCurrencyName || item.showPairsName || item.name || item.pairsName
          }}</p>
          <p class="p2" v-if="item.baseCurrencyName">{{ item.tokenCur }}</p>
        </div> -->
        <div class="rank_box_text">
          <div style="color: rgba(255, 255, 255, 0.85); font-size: 15px">
            <span v-if="item.type === 'CONTRACT'">{{ item.pairsName }}</span>
            <span v-else> {{ item.symbol }}/USD</span>
          </div>
          <div class="volume" v-if="item.volume">
            {{ $t('volume1') }} {{ handleUnit(item.volume) }}</div
          >
        </div>
        <div
          class="width2"
          :class="Number(item.updown) > 0 || Number(item.chg) > 0 ? 'font_green' : 'font_red'"
        >
          <p class="p3">{{ item.lastPrice || item.price }}</p>
          <p class="red">{{ item.chgPct || item.updown }}%</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .maketsList {
    .maketsList-list {
      .li {
        display: flex;
        align-items: center;
        border-radius: 16px;
        box-shadow: 0px 2px 4px 0px rgba(255, 255, 255, 0.07);
        background: $body;
        padding: 20px 20px;
        margin-bottom: 10px;
        .img_box {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin-right: 16px;
          background: #242424;
          position: relative;
          .flag {
            width: 40px;
            height: 40px;
            position: absolute;
          }
          .flag1 {
            top: 12px;
            left: 10px;
            & > img {
              border-radius: 50%;
            }
          }
          .flag2 {
            top: 30px;
            left: 30px;
          }
        }

        .btns {
          width: 120px;
          text-align: center;
          height: 72px;
          line-height: 72px;
          border-radius: 900px;
          color: #0063f5;
          font-size: 28px;
          background-color: #e5effe;
        }

        .p1 {
          color: rgba(255, 255, 255, 0.85);
          font-size: 30px;
          font-weight: 700;
          margin-bottom: 15px;
        }

        .p2 {
          color: rgba(255, 255, 255, 0.45);
          font-size: 24px;
        }

        .p3 {
          font-size: 32px;
          margin-bottom: 12px;
        }

        .red {
          font-size: 24px;
        }

        .green {
          color: rgb(45, 189, 133);
          font-size: 24px;
        }
        .width1 {
          width: calc(100% - 80px - 16px - 120px - 30%);
          word-break: break-all;
        }
        .rank_box_text {
          width: calc(100% - 80px - 16px - 120px - 30%);
          word-break: break-all;
          flex: 1;
          .volume {
            margin-top: 12px;
            color: rgba(255, 255, 255, 0.45);
            font-size: 24px;
          }
        }
        .width2 {
          width: 30%;
          text-align: right;
          word-break: break-all;
        }
      }
    }
  }
</style>
